<template>
  <view class="container">
    <!-- 加载状态 -->
    <view v-if="isLoading" class="loading-overlay">
      <view class="loading-content">
        <view class="loading-icon">
          <uni-icons type="spinner-cycle" size="30" color="#3B82F6"></uni-icons>
        </view>
        <text class="loading-text">数据加载中...</text>
      </view>
    </view>

    <view v-else>
      <!-- 导航栏 -->
      <view class="nav-bar">
        <view class="nav-item" :class="{ active: currentView === 'day' }" @click="switchView('day')">
          今日监测
        </view>
        <view class="nav-item" :class="{ active: currentView === 'week' }" @click="switchView('week')">
          本周趋势
        </view>
      </view>

      <!-- 今日心率监测 -->
      <view v-if="currentView === 'day'" class="day-view">
        <!-- 心率概览卡片 -->
        <view class="card">
          <view class="card-header">
            <text class="title">今日心率监测</text>
            <view class="stats">
              <text class="stat-value">{{ heartRate.day.avg }} bpm</text>
              <text class="stat-label">平均心率</text>
            </view>
          </view>

          <!-- 心率图表 -->
          <view class="charts-box">
            <qiun-data-charts v-if="hrDayData" type="area" :opts="hrDayOpts" :chartData="hrDayData" />
          </view>

          <!-- 心率数据摘要 -->
          <view class="hr-summary">
            <view class="hr-item">
              <text class="hr-label">最高心率</text>
              <text class="hr-value">{{ heartRate.day.max }} bpm</text>
              <text class="hr-time">{{ heartRate.day.maxTime }}</text>
            </view>
            <view class="hr-divider"></view>
            <view class="hr-item">
              <text class="hr-label">最低心率</text>
              <text class="hr-value">{{ heartRate.day.min }} bpm</text>
              <text class="hr-time">{{ heartRate.day.minTime }}</text>
            </view>
          </view>
        </view>

        <!-- 心率区间卡片 -->
        <view class="card hr-zones-card">
          <view class="card-header">
            <text class="title">今日心率区间分布</text>
          </view>
          <view class="zones-indicator">
            <view class="zone-bar">
              <view class="zone-segment" v-for="(zone, index) in hrZones.day" :key="index" :style="{
                width: zone.percentage + '%',
                backgroundColor: zone.color
              }"></view>
            </view>
            <view class="zones-labels">
              <view class="zone-label-item" v-for="(zone, index) in hrZones.day" :key="index">
                <view class="zone-color" :style="{ backgroundColor: zone.color }"></view>
                <text class="zone-name">{{ zone.name }}</text>
                <text class="zone-percentage">{{ zone.percentage }}%</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 本周心率监测 -->
      <view v-else class="week-view">
        <!-- 周趋势图表 -->
        <view class="card">
          <view class="card-header">
            <text class="title">本周心率趋势</text>
            <view class="stats">
              <text class="stat-value">{{ heartRate.week.avg }} bpm</text>
              <text class="stat-label">周平均</text>
            </view>
          </view>
          <view class="charts-box">
            <qiun-data-charts type="line" :opts="hrWeekOpts" :chartData="hrWeekData" />
          </view>
        </view>

        <!-- 每日心率数据 -->
        <view class="card">
          <view class="card-header">
            <text class="title">每日心率数据</text>
          </view>
          <view class="week-hr-grid">
            <view class="week-hr-item" v-for="(day, index) in heartRate.week.days" :key="index">
              <text class="week-day">{{ day.name }}</text>
              <view class="week-hr-value">
                <text class="value">{{ day.avg }}</text>
                <text class="unit">bpm</text>
              </view>
              <view class="week-hr-range">
                <text class="min">{{ day.min }}</text>
                <text class="separator">~</text>
                <text class="max">{{ day.max }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 周心率区间分析 -->
        <view class="card">
          <view class="card-header">
            <text class="title">周心率区间分析</text>
          </view>
          <view class="week-zones-chart">
            <qiun-data-charts type="radar" :opts="hrRadarOpts" :chartData="hrRadarData" />
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useHealthData } from '@/store/modules/useHealthData'
import { get } from '@/utils/request'
// import { uniIcons } from '@dcloudio/uni-ui'

const healthDataStore = useHealthData()

// 视图状态
const currentView = ref('day')
const isLoading = ref(true)

// 心率数据
const heartRate = ref({
  day: {
    avg: 0,
    max: 0,
    maxTime: "--:--",
    min: 0,
    minTime: "--:--",
    chartData: null
  },
  week: {
    avg: 0,
    days: [
      { name: "周一", avg: 0, min: 0, max: 0 },
      { name: "周二", avg: 0, min: 0, max: 0 },
      { name: "周三", avg: 0, min: 0, max: 0 },
      { name: "周四", avg: 0, min: 0, max: 0 },
      { name: "周五", avg: 0, min: 0, max: 0 },
      { name: "周六", avg: 0, min: 0, max: 0 },
      { name: "周日", avg: 0, min: 0, max: 0 }
    ]
  }
})

// 心率区间数据
const hrZones = ref({
  day: [
    { name: "休息区", range: "<60", percentage: 0, color: "#93C5FD" },
    { name: "燃脂区", range: "60-70", percentage: 0, color: "#60A5FA" },
    { name: "有氧区", range: "70-80", percentage: 0, color: "#3B82F6" },
    { name: "极限区", range: "80+", percentage: 0, color: "#EE6666" }
  ],
  week: [
    { name: "休息区", data: [0, 0, 0, 0, 0, 0, 0] },
    { name: "燃脂区", data: [0, 0, 0, 0, 0, 0, 0] },
    { name: "有氧区", data: [0, 0, 0, 0, 0, 0, 0] },
    { name: "极限区", data: [0, 0, 0, 0, 0, 0, 0] }
  ]
})

// 图表配置
const hrDayOpts = ref({
  color: ["#EE6666"],
  padding: [15, 15, 10, 15],
  enableScroll: false,
  legend: {
    show: false
  },
  xAxis: {
    disableGrid: true,
    axisLineColor: "#E4E7ED",
    boundaryGap: "justify"
  },
  yAxis: {
    gridType: "dash",
    dashLength: 4,
    splitNumber: 5,
    data: [{
      min: 50,
      max: 120,
      axisLineColor: "#E4E7ED",
      splitLineColor: "#F7F8FA",
      format: val => `${val} bpm`
    }]
  },
  extra: {
    area: {
      type: "curve",
      opacity: 0.1,
      addLine: true,
      width: 3,
      gradient: true,
      activeType: "hollow"
    },
    markLine: {
      type: "dash",
      dashLength: 4,
      data: [
        { value: 60, lineColor: "#3B82F6", lineWidth: 1, labelColor: "#3B82F6", labelFontSize: 20 },
        { value: 100, lineColor: "#EE6666", lineWidth: 1, labelColor: "#EE6666", labelFontSize: 20 }
      ]
    }
  }
})

const hrWeekOpts = ref({
  color: ["#EE6666"],
  padding: [15, 15, 10, 15],
  enableScroll: false,
  legend: {
    show: false
  },
  xAxis: {
    disableGrid: true,
    axisLineColor: "#E4E7ED"
  },
  yAxis: {
    gridType: "dash",
    dashLength: 4,
    splitNumber: 5,
    data: [{
      min: 50,
      max: 120,
      axisLineColor: "#E4E7ED",
      splitLineColor: "#F7F8FA",
      format: val => `${val} bpm`
    }]
  },
  extra: {
    line: {
      type: "curve",
      width: 3,
      activeType: "hollow"
    }
  }
})

const hrRadarOpts = ref({
  color: ["#93C5FD", "#60A5FA", "#3B82F6", "#EE6666"],
  padding: [15, 15, 15, 15],
  dataLabel: false,
  enableScroll: false,
  legend: {
    show: true,
    position: "right",
    lineHeight: 25
  },
  extra: {
    radar: {
      gridType: "radar",
      gridColor: "#CCCCCC",
      gridCount: 3,
      opacity: 0.2,
      max: 100,
      labelShow: true,
      border: true
    }
  }
})

// 图表数据
const hrDayData = computed(() => {
  // 使用后端提供的 chartData
  return heartRate.value.day.chartData || {
    categories: [],
    series: []
  };
})

const hrWeekData = computed(() => ({
  categories: heartRate.value.week.days.map(day => day.name),
  series: [
    {
      name: "平均心率",
      data: heartRate.value.week.days.map(day => day.avg)
    }
  ]
}))

const hrRadarData = computed(() => {
  if (!heartRate.value.week.days || !hrZones.value.week) {
    return {
      categories: [],
      series: []
    }
  }

  return {
    categories: heartRate.value.week.days.map(day => day.name),
    series: hrZones.value.week.map(zone => ({
      name: zone.name,
      data: zone.data
    }))
  }
})

// 方法
const switchView = (view) => {
  currentView.value = view
  loadData() // 切换视图时重新加载数据
}

// 加载数据
const loadData = async () => {
  try {
    isLoading.value = true
    const userId = healthDataStore.getCurUserId 

    const res = await get(
      `/health/${userId}/statistics?period=${currentView.value}&type=heartRate`,
      'api/v1'
    )

    if (res.code === 200 && res.data) {
      if (currentView.value === 'day') {
        heartRate.value.day = {
          avg: res.data.avg,
          max: res.data.max,
          maxTime: res.data.maxTime,
          min: res.data.min,
          minTime: res.data.minTime
        }
        // 更新心率区间数据
        if (res.data.zones) {
          hrZones.value.day = res.data.zones
        }
        // 保存日趋势图表数据
        if (res.data.chartData) {
          heartRate.value.day.chartData = res.data.chartData
        }
      } else {
        heartRate.value.week = {
          ...heartRate.value.week,
          ...res.data
        }
        // 更新周心率区间数据
        if (res.data.zones) {
          hrZones.value.week = res.data.zones
        }
      }
    }
  } catch (error) {
    console.error('Failed to load heart rate data:', error)
    uni.showToast({
      title: '数据加载失败',
      icon: 'none'
    })
  } finally {
    // 添加一个小延迟，确保数据完全准备好
    setTimeout(() => {
      isLoading.value = false
    }, 300)
  }
}

// 组件挂载时加载数据
onMounted(async () => {
  await loadData()
})

// 监听视图切换
watch(currentView, async () => {
  await loadData()
})
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  background-color: #F7F8FA;
  min-height: 100vh;
}

/* 导航栏样式 */
.nav-bar {
  display: flex;
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);

  .nav-item {
    flex: 1;
    text-align: center;
    padding: 24rpx 0;
    font-size: 28rpx;
    color: #666;
    position: relative;
    transition: all 0.3s;

    &.active {
      color: #EE6666;
      font-weight: 500;

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 80rpx;
        height: 4rpx;
        background-color: #EE6666;
        border-radius: 2rpx;
      }
    }
  }
}

/* 卡片通用样式 */
.card {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  padding: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.04);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;

  .title {
    font-size: 32rpx;
    font-weight: 500;
    color: #333;
  }

  .stats {
    display: flex;
    flex-direction: column;
    align-items: flex-end;

    .stat-value {
      font-size: 28rpx;
      font-weight: 500;
      color: #EE6666;
    }

    .stat-label {
      font-size: 24rpx;
      color: #999;
      margin-top: 4rpx;
    }
  }
}

/* 图表容器 */
.charts-box {
  width: 100%;
  height: 400rpx;
}

/* 心率数据摘要 */
.hr-summary {
  display: flex;
  justify-content: space-between;
  margin-top: 30rpx;

  .hr-item {
    flex: 1;
    text-align: center;

    .hr-label {
      font-size: 26rpx;
      color: #999;
      display: block;
    }

    .hr-value {
      font-size: 36rpx;
      font-weight: 500;
      color: #333;
      display: block;
      margin: 8rpx 0;
    }

    .hr-time {
      font-size: 24rpx;
      color: #999;
      display: block;
    }
  }

  .hr-divider {
    width: 1rpx;
    background-color: #F0F0F0;
    margin: 0 20rpx;
  }
}

/* 心率区间卡片 */
.hr-zones-card {
  .zones-indicator {
    margin-top: 20rpx;

    .zone-bar {
      display: flex;
      height: 24rpx;
      border-radius: 12rpx;
      overflow: hidden;
      margin-bottom: 20rpx;
    }

    .zones-labels {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 20rpx;

      .zone-label-item {
        display: flex;
        align-items: center;

        .zone-color {
          width: 20rpx;
          height: 20rpx;
          border-radius: 4rpx;
          margin-right: 12rpx;
        }

        .zone-name {
          font-size: 26rpx;
          color: #666;
          margin-right: 8rpx;
        }

        .zone-percentage {
          font-size: 26rpx;
          color: #333;
          font-weight: 500;
        }
      }
    }
  }
}

/* 每周心率数据网格 */
.week-hr-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
  margin-top: 20rpx;

  .week-hr-item {
    padding: 20rpx;
    background-color: #F7F8FA;
    border-radius: 12rpx;

    .week-day {
      font-size: 28rpx;
      color: #666;
      display: block;
      margin-bottom: 12rpx;
    }

    .week-hr-value {
      display: flex;
      align-items: flex-end;
      margin-bottom: 8rpx;

      .value {
        font-size: 36rpx;
        font-weight: 500;
        color: #333;
        margin-right: 8rpx;
      }

      .unit {
        font-size: 24rpx;
        color: #999;
        padding-bottom: 4rpx;
      }
    }

    .week-hr-range {
      font-size: 24rpx;
      color: #999;

      .min {
        color: #3B82F6;
      }

      .max {
        color: #EE6666;
      }

      .separator {
        margin: 0 8rpx;
      }
    }
  }
}

/* 雷达图容器 */
.week-zones-chart {
  width: 100%;
  height: 500rpx;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.95);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;

  .loading-content {
    text-align: center;
    padding: 30rpx;
    border-radius: 20rpx;
    background-color: rgba(255, 255, 255, 0.8);
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);

    .loading-icon {
      margin-bottom: 20rpx;
      animation: rotate 1s linear infinite;
    }

    .loading-text {
      font-size: 28rpx;
      color: #666;
      font-weight: 500;
    }
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}
</style>